package com.wanlian.context.Notice;

import com.wanlian.common.UrlConfig;
import com.wanlian.jpush.service.PushUtils;
import com.wanlian.vo.NoticeMsgResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
public class NoticeTask {

    @Autowired
    private PushUtils pushUtils;

    @Autowired
    private UrlConfig urlConfig;

    @PostConstruct
    private void calc() {
        // 发送
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        sendMsg();
                        Thread.sleep(200);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        // 整理消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        tidyMsg();
                        Thread.sleep(200);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private synchronized void sendMsg() {
        NoticeMsgResultVo vo = NoticeMsgContext.get();
        if (vo != null) {
            if (!vo.isAll()) {
                List<String> alias = new ArrayList<>();
                alias.add(vo.getUser().getUserTag());
                pushUtils.sendAlias(vo.getNoticeMsg().getTitle(), alias, urlConfig.isbProduct());
                NoticeManager.addRecords(vo.getUser().getId());
            } else {
                pushUtils.sendAllsetNotification(vo.isSingleAndroid(), vo.isSingleIOS(), vo.getNoticeMsg().getTitle(), vo.getNoticeMsg().getAttr1(), urlConfig.isbProduct());
            }
        }
    }

    private synchronized void tidyMsg() {
        NoticeManager.tidyMsg();
    }
}
